package com.tlgen.orm.components.dataSource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

public class DynamicDataSource extends AbstractRoutingDataSource {
    private final DataSource defaultDataSource;
    private final Map<Object, Object> targetDataSources;

    public DynamicDataSource(DataSource defaultDataSource, Map<String, DataSource> targetDataSources) {
        this.defaultDataSource = defaultDataSource;
        this.targetDataSources = new HashMap<>(targetDataSources);
        super.setDefaultTargetDataSource(defaultDataSource);
        super.setTargetDataSources(this.targetDataSources);
        super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder.getCurrentDataSource();
    }

    public void addDataSource(String name, DataSource dataSource) {
        targetDataSources.put(name, dataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }

    public void removeDataSource(String name) {
        targetDataSources.remove(name);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }

}